package com.jgp.third.pay.service.impl;

import com.jgp.common.utils.JGPUtil;
import com.jgp.security.config.SecUserAdapter;
import com.jgp.security.pojo.UserInfo;
import com.jgp.security.props.SecurityConfigPropBean;
import com.jgp.sys.query.Operator;
import com.jgp.sys.query.QueryFilterList;
import com.jgp.third.pay.model.PaymentConfig;
import com.jgp.third.pay.model.PaymentMode;
import com.jgp.third.pay.pojo.PaymentParam;
import com.jgp.third.pay.repository.PaymentConfigRepository;
import com.jgp.third.pay.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Objects;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2018/11/8
 */
@Service
public class PayServiceImpl implements PayService {
    
    @Autowired
    private PaymentConfigRepository repository;
    
    @Autowired
    private SecUserAdapter userAdapter;
    
    @Autowired
    private SecurityConfigPropBean securityConfigPropBean;
    
    
    @Override
    public List<PaymentConfig> queryAllPaymentsForCurrentUser() {
        QueryFilterList filters = new QueryFilterList();
        UserInfo user = userAdapter.currentUser();
        
        if (securityConfigPropBean.getEnabled()) {
            Assert.notNull(user, "找不到当前用户");
            filters.addFilter("userId", Operator.eq, user.getId());
        }
        
        return repository.read(filters);
    }
    
    @Transactional
    @Override
    public PaymentConfig savePaymentConfig(PaymentConfig config, PaymentParam param) {
        config.setConfig(JGPUtil.toJson(param));
        UserInfo user = userAdapter.currentUser();
        if (securityConfigPropBean.getEnabled()) {
            Assert.notNull(user, "找不到当前用户");
            config.setUserId(user.getId());
        }
        
        return repository.createOrUpdate(config);
    }
    
    @Override
    public PaymentConfig queryPaymentConfigById(String configId) {
        return repository.read(configId);
    }
    
    @Override
    public boolean checkPaymentModeUniqueForCurrentUser(PaymentMode mode) {
        UserInfo user = userAdapter.currentUser();
        QueryFilterList filters = new QueryFilterList();
        if(Objects.nonNull(user)){
            filters.addFilter("userId",Operator.eq,user.getId());
        }
        filters.addFilter("mode", Operator.eq, mode);
        return repository.count(filters)>0;
    }
    
    
}
